package com.example.shiyan4;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.util.ServiceConfigurationError;

public class MainActivity extends AppCompatActivity {
    Button bind,unbind,getServiceStatus;
    BindService.MyBinder binder;
    boolean ifbind=false;
    private ServiceConnection conn =new ServiceConnection(){

        public void onServiceConnected(ComponentName name, IBinder service){
            System.out.println("--Service Connected--");
            binder=(BindService.MyBinder) service;
            ifbind=true;

        }
        public void onServiceDisconnected(ComponentName name){
            System.out.println("--Service Disconnected");
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bind=findViewById(R.id.bind);
        unbind=findViewById(R.id.unbind);
        getServiceStatus=findViewById(R.id.getServiceStatus);
        final Intent intent=new Intent(this,BindService.class);

        bind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bindService(intent,conn,BIND_AUTO_CREATE);
            }
        });

        unbind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                unbindService(conn);

            }
        });
        getServiceStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if( !ifbind)
                   Toast.makeText(MainActivity.this,"未绑定",Toast.LENGTH_SHORT).show();
                else
                Toast.makeText(MainActivity.this,"Service的count值为"+binder.getCount(),Toast.LENGTH_SHORT).show();
            }
        });
    }
}
